import type { AxiosRequestConfig } from 'axios'
import { useAuthStore } from '@/stores/auth/auth'
import { useUserStore } from '@/stores/auth/user'

/**
 * 从全局状态或 localStorage 读取 token，优先级：authStore -> userStore -> localStorage('token')
 */
export function readToken(): string | undefined {
  try {
    const auth = useAuthStore()
    if (auth?.accessToken) return auth.accessToken
  } catch {}
  try {
    const user = useUserStore() as any
    if (user?.token) return user.token as string
  } catch {}
  try {
    const t = localStorage.getItem('token')
    if (t) return t
  } catch {}
  return undefined
}

/**
 * 构造认证头
 * 可通过环境变量覆盖：
 *   VITE_AUTH_HEADER 头名（默认 Authorization）
 *   VITE_AUTH_SCHEME 前缀（默认 Bearer；设为空字符串则不加前缀）
 */
export function buildAuthHeader(token?: string): Record<string, string> {
  if (!token) return {}
  const headerName = (import.meta as any)?.env?.VITE_AUTH_HEADER || 'Authorization'
  const scheme = (import.meta as any)?.env?.VITE_AUTH_SCHEME
  const shouldPrefix = headerName.toLowerCase() === 'authorization' && (scheme ?? 'Bearer')
  const value = shouldPrefix ? `${shouldPrefix} ${token}` : token
  return { [headerName]: value }
}

/** 合并请求头（调用方自定义优先覆盖） */
export function mergeHeaders(
  base?: AxiosRequestConfig['headers'],
  extra?: AxiosRequestConfig['headers'],
): AxiosRequestConfig['headers'] {
  return { ...(base || {}), ...(extra || {}) }
}

/**
 * 给请求配置自动注入认证与自定义头
 */
export function withAuthHeaders(
  config: AxiosRequestConfig & { skipAuth?: boolean } = {},
): AxiosRequestConfig {
  const token = config.skipAuth ? undefined : readToken()
  const auth = config.skipAuth ? {} : buildAuthHeader(token)
  config.headers = mergeHeaders(auth, config.headers)
  return config
}
